<template>
  <div id="my-message">
    <el-card class="box-card card1" v-loading="loading">
      <div class="box-card-top">个人信息</div>
      <div class="body" v-loading="loading">
        <div class="body-top">
          <div class="aa">
            <img
              :src="$server + adminInfo.avatar"
              ref="previewImg"
              class="user-avatar"
              width="150px"
              height="150px"
              @change="changeImg"
            />
            <input
              type="file"
              id="file"
              name="file"
              ref="uploadImg"
              accept="image/png, image/jpeg, image/gif, image/jpg"
              class="upload-input"
              @change="changeImg"
            />
            <div class="bg">
              <i class="el-icon-camera-solid"></i>
            </div>
          </div>
        </div>
        <div class="body-content" style="padding-top:20px">
          <div class="flex">
            <div class="el-icon-user">
              <span style="padding-left:4px">用户名称：</span>
            </div>
            <div>{{adminInfo.name}}</div>
          </div>
          <div class="flex">
            <div class="el-icon-female">
              <span style="padding-left:4px">性别：</span>
            </div>
            <div>{{adminInfo.sex}}</div>
          </div>
          <div class="flex">
            <div class="el-icon-phone-outline">
              <span style="padding-left:4px">手机号码：</span>
            </div>
            <div>{{adminInfo.phone}}</div>
          </div>
          <div class="flex">
            <div class="el-icon-date">
              <span style="padding-left:4px">出生日期：</span>
            </div>
            <div>{{adminInfo.birthday}}</div>
          </div>
        </div>
      </div>
    </el-card>
    <el-card class="box-card card2" v-loading="loading">
      <div class="box-card-top">基本资料</div>
      <div class="body" v-loading="loading">
        <div class="body-content" style="padding-top:20px">
          <el-tabs v-model="activeName" @tab-click="changeTab">
            <el-tab-pane label="基本资料" name="first">
              <el-form ref="form" :rules="rules" :model="form" label-width="100px">
                <el-form-item label="用户名称" placeholder="请输入" prop="name">
                  <el-input v-model="form.name"></el-input>
                </el-form-item>
                <el-form-item label="性别" prop="sex">
                  <el-select v-model="form.sex" placeholder="请输入">
                    <el-option label="男" value="男"></el-option>
                    <el-option label="女" value="女"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="手机号码" placeholder="请输入" prop="phone">
                  <el-input v-model="form.phone"></el-input>
                </el-form-item>
                <el-form-item label="出生日期" placeholder="请输入" prop="birthday">
                  <el-date-picker
                    v-model="form.birthday"
                    value-format="yyyy-MM-dd"
                    type="date"
                    placeholder="选择日期"
                  ></el-date-picker>
                </el-form-item>
                <el-form-item style="display:flex;justify-content: flex-end;">
                  <el-button type="primary" @click="handleBaoCun(false)">保存</el-button>
                  <el-button @click="resetForm">重置</el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>
            <el-tab-pane label="修改密码" name="second">
              <el-form ref="form2" :rules="rules2" :model="form2" label-width="100px">
                <el-form-item label="旧密码" placeholder="请输入" prop="oldPassword">
                  <el-input type="password" show-password v-model="form2.oldPassword"></el-input>
                </el-form-item>
                <el-form-item label="新密码" placeholder="请输入" prop="newPassword">
                  <el-input type="password" show-password v-model="form2.newPassword"></el-input>
                </el-form-item>
                <el-form-item label="确认密码" placeholder="请输入" prop="Password">
                  <el-input type="password" show-password v-model="form2.Password"></el-input>
                </el-form-item>
                <el-form-item style="display:flex;justify-content: flex-end;">
                  <el-button type="primary" @click="handleBaoCun(true)">保存</el-button>
                  <el-button @click="resetForm">重置</el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import {
  upLoadImg,
  getAdminInfo,
  updateAdminInfo,
  updateAdminPassword,
} from '../../../api'
export default {
  name: 'MySessage',
  data() {
    let checkPhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入手机号码'))
      } else {
        if (/^1[3|4|5|6|7|8][0-9]{9}$/.test(value)) {
          callback()
        } else {
          callback(new Error('请输入正确格式的手机号码'))
        }
      }
    }
    let checkPassword = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入手机号码'))
      } else {
        if (this.form2.newPassword === this.form2.Password) {
          callback()
        } else {
          callback(new Error('两次密码不一致'))
        }
      }
    }
    return {
      loading: false,
      adminInfo: {},
      activeName: 'first',
      form: {},
      rules: {
        name: [{ required: true, message: '请输入名字', trigger: 'blur' }],
        phone: [
          { required: true, message: '请输入电话', trigger: 'blur' },
          { validator: checkPhone, trigger: 'blur' },
        ],
        sex: [{ required: true, message: '请选择性别', trigger: 'blur' }],
        birthday: [{ required: true, message: '请选择日期', trigger: 'blur' }],
      },
      form2: {},
      rules2: {
        oldPassword: [
          { required: true, message: '请输入密码', trigger: 'blur' },
        ],
        newPassword: [
          { required: true, message: '请输入密码', trigger: 'blur' },
        ],
        Password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { validator: checkPassword, trigger: 'blur' },
        ],
      },
    }
  },
  created() {
    this.loadAdminInfo()
  },
  methods: {
    loadAdminInfo() {
      if (window.sessionStorage.getItem('token')) {
        //如果有就获取管理员的名字
        getAdminInfo()
          .then((res) => {
            if (res.success_code === 200) {
              this.adminInfo = res.data
              this.form = {
                adminId: this.adminInfo.admin_id,
                name: this.adminInfo.name,
                birthday: this.adminInfo.birthday,
                phone: this.adminInfo.phone,
                sex: this.adminInfo.sex,
                avatar: this.adminInfo.avatar,
              }
            } else {
              this.$message.error('请先登录！')
            }
          })
          .finally(() => this.$Loading())
      }
    },
    handleBaoCun(res) {
      if (res) {
        this.$refs.form.validate().then(() => {
          updateAdminPassword(
            this.adminInfo.admin_id,
            this.form2.oldPassword,
            this.form2.newPassword
          )
            .then((res) => {
              if (res.success_code === 200) {
                this.$message.success('修改密码成功！')
                this.loadAdminInfo()
              } else {
                this.$message.error(res.message)
                this.$refs.form2.resetFields()
              }
            })
            .finally(() => this.$Loading())
        })
      } else {
        this.$refs.form.validate().then(async () => {
          //图片
          let formData = new FormData()
          formData.append('file', this.$refs.uploadImg.files[0])
          let json = await upLoadImg(formData)
          if (json.success_code === 200) {
            if (json.data.length) {
              this.form.avatar = '/images/avatar/' + json.data[0].filename
            }
            updateAdminInfo(
              this.form.adminId,
              this.form.avatar,
              this.form.name,
              this.form.sex,
              this.form.phone,
              this.form.birthday
            )
              .then((res) => {
                if (res.success_code === 200) {
                  this.$message.success('修改信息成功！')
                  this.loadAdminInfo()
                  this.$parent.handleupdate()
                } else {
                  this.$message.error(res.message)
                  this.$refs.form.resetFields()
                }
              })
              .finally(() => this.$Loading())
          }
        })
      }
      this.$refs.form.clearValidate()
      this.$refs.form2.clearValidate()
    },
    resetForm() {
      this.$refs.form.resetFields()
      this.$refs.form2.resetFields()
    },
    changeTab() {
      this.$refs.form.clearValidate()
      this.$refs.form2.clearValidate()
    },
    // 头像
    changeImg(e) {
      let reader = new FileReader()
      reader.readAsDataURL(this.$refs.uploadImg.files[0]) //发起异步请求
      let _this = this
      reader.onload = function () {
        //读取完成后，将结果赋值给img的src
        _this.$refs.previewImg.src = this.result
        _this.form.avatar = this.result
      }
    },
  },
}
</script>

<style lang="stylus" scoped>
#my-message {
  padding: 20px;
  flex-direction: row;

  .card1 {
    width: 450px;

    &-top {
      height: 32px;
      padding: 0;
      border-bottom: 1px solid #ddd;
    }

    .body {
      width: 100%;
      height: 100%;
      display: flex;
      flex-direction: column;

      &-top {
        display: flex;
        justify-content: center;
        margin-top: 20px;

        .user-avatar {
          border-radius: 50%;
          display: flex;
          justify-content: center;
        }
      }

      &-body-content {
        flex: 1;
      }
    }
  }

  .card2 {
    flex: 1;
    margin-left: 8px;
  }

  .upload-input {
    position: absolute;
    opacity: 0;
    top: 19%;
    z-index: 2;
    width: 155px;
    height: 155px;
    cursor: pointer;
  }

  .el-icon-camera-solid {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index: 1;
    color: #fff;
    font-size: 30px;
  }

  .bg {
    position: absolute;
    top: 20%;
    z-index: 1;
    opacity: 0;
    width: 150px;
    height: 150px;
    border-radius: 50%;
    background: rgba(0, 0, 0, 0.5);
  }

  .aa:hover .bg {
    opacity: 1;
  }
}

.flex {
  display: flex;
  justify-content: space-between;
  border-bottom: 1px solid #ddd;
  padding-bottom: 8px;
  margin-bottom: 20px;
  color: #676A6C;
}
</style>
